<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hOut">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100px;height:100px">
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ getFormOfEmployment(row.formOfEmployment) }}
              <!-- {{ row }} -->
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="Roles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 15]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增或编辑的弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <addorEdit
        ref="refFrom"
        @success="hSuccess"
        @close="close"
      />
    </el-dialog>
    <!-- 员工管理的弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="showRoleDialog"
    >
      <assignRole v-if="showRoleDialog" :role-id="roleId" @close="showRoleDialog = false" />
    </el-dialog>
  </div>
</template>

<script>
import assignRole from './assignRole.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addorEdit from './empDialog'

// console.log(EmployeeEnum.hireType)
const hire = {}
EmployeeEnum.hireType.forEach(item => {
  hire[item.id] = item.value
})
export default {
  components: {
    addorEdit, assignRole
  },
  data() {
    return {
      roleId: '',
      showRoleDialog: false, // 控制分配角色的显示与隐藏
      showDialog: false, // 控制弹窗的显示与隐藏
      list: [], // 用来保存员工列表
      total: 0, // 列表总数
      page: 1,
      size: 2
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    Roles(id) {
      this.showRoleDialog = true
      this.roleId = id
    },
    dataFormat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1. 获取表头
      const one = list[0]
      let headers = []
      if (one) {
        headers = Object.keys(one).map(enkey => {
          return mapInfo[enkey]
        })
      }
      // 2. 将每一个对象对象中的值存到一个数组中 ，将每个数组存储到大数组中
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },
    async hOut() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log('getEmployeeList', res)
        const { headers, data } = this.dataFormat(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
        // 3.调用excel.export_json_to_excel将格式好的数据写入Excel文件中
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        // 保存数据
      } catch (err) {
        console.log('getEmployeeList', err)
      }
    },
    hClose() {
      this.$refs.refFrom.resetForm()
    },
    close() {
      this.showDialog = false
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.showDialog = false
      this.loadEmployeeList()
    },
    hAdd() {
      this.showDialog = true
    },
    // 删除功能
    async hDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
        // 保存数据
      } catch (err) {
        console.log('delEmployee', err)
      }
    },
    // 聘用形式渲染
    getFormOfEmployment(data) {
      return hire[data] || '未知'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 获取员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        // console.log('getEmployeeList', res)
        this.list = res.data.rows
        this.total = res.data.total
        // 保存数据
      } catch (err) {
        console.log('getEmployeeList', err)
      }
    }
  }
}
</script>

